from flask import Flask, request, jsonify
# from some_nlp_library import get_answer  # 假设你有一个NLP库来处理问题并返回答案
from flask_cors import CORS, cross_origin

app = Flask(__name__)
CORS(app)  # 这将为所有路由启用CORS


@cross_origin()
@app.route('/api/answer', methods=['POST'])
def answer():
    data = request.get_json()
    question = data['question']+"，回答不要超过10字"
    print("我收到了你的问题：" + question)
    from sparkai.llm.llm import ChatSparkLLM, ChunkPrintHandler
    from sparkai.core.messages import ChatMessage

    # 星火认知大模型Spark Max的URL值，其他版本大模型URL值请前往文档（https://www.xfyun.cn/doc/spark/Web.html）查看
    SPARKAI_URL = 'wss://spark-api.xf-yun.com/v3.5/chat'
    # 星火认知大模型调用秘钥信息，请前往讯飞开放平台控制台（https://console.xfyun.cn/services/bm35）查看
    SPARKAI_APP_ID = 'd16f688b'
    SPARKAI_API_SECRET = 'M2Q2ZDM3MGY4YzZmYzgyM2NiNDdmNjAx'
    SPARKAI_API_KEY = 'f5871f26e082699875dcdc77ce2cb0f9'
    # 星火认知大模型Spark Max的domain值，其他版本大模型domain值请前往文档（https://www.xfyun.cn/doc/spark/Web.html）查看
    SPARKAI_DOMAIN = 'generalv3.5'

    # if __name__ == '__main__':
    spark = ChatSparkLLM(
        spark_api_url=SPARKAI_URL,
        spark_app_id=SPARKAI_APP_ID,
        spark_api_key=SPARKAI_API_KEY,
        spark_api_secret=SPARKAI_API_SECRET,
        spark_llm_domain=SPARKAI_DOMAIN,
        streaming=False,
    )
    messages = [ChatMessage(
        role="user",
        content=question
    )]
    handler = ChunkPrintHandler()
    a = spark.generate([messages], callbacks=[handler])
    print("大模型回答了：")
    print(a)
    # answer = get_answer(question)  # 调用NLP库来获取答案
    return jsonify({'answer': a.generations[0][0].text})


if __name__ == '__main__':
    app.run(debug=True)
